import mysql.connector
from datetime import datetime, timedelta
import threading
import time

class WhiteListCache:
    _instance = None
    _lock = threading.Lock()
    
    def __new__(cls):
        with cls._lock:
            if cls._instance is None:
                cls._instance = super(WhiteListCache, cls).__new__(cls)
            return cls._instance

    def __init__(self):
        if not hasattr(self, 'initialized'):
            self.cache = {}
            self.last_update_time = {}
            self.update_interval = 600  # 10分钟更新一次
            self.initialized = True

    def get_white_list(self, conn, shop_type):
        """获取白名单数据，如果缓存过期则更新"""
        current_time = datetime.now()
        
        # 检查是否需要更新缓存
        if (shop_type not in self.last_update_time or 
            current_time - self.last_update_time[shop_type] > timedelta(seconds=self.update_interval)):
            
            with self._lock:
                try:
                    cursor = conn.cursor()
                    sql = f'SELECT distinct shop_name FROM shopwhite_list WHERE shop_type="{shop_type}"'
                    cursor.execute(sql)
                    results = cursor.fetchall()
                    
                    # 更新缓存
                    self.cache[shop_type] = [row[0] for row in results]
                    self.last_update_time[shop_type] = current_time
                    
                except Exception as e:
                    print(f"Error updating white list cache for {shop_type}: {e}")
                    # 如果发生错误且缓存中没有数据，返回空列表
                    if shop_type not in self.cache:
                        self.cache[shop_type] = []
                finally:
                    cursor.close()
        
        return self.cache.get(shop_type, [])

    def force_refresh(self, conn, shop_type):
        """强制刷新指定类型的缓存"""
        if shop_type in self.last_update_time:
            del self.last_update_time[shop_type]
        return self.get_white_list(conn, shop_type) 